import React, {useState} from "react"
import {Button, Form, PageHeader, Radio, Select, Table, Upload, message, Progress} from "antd"
import {read} from "zr-react-toolbox"
import {HOST} from "../../../project-config"
import LoadingOutlined from "@ant-design/icons/es/icons/LoadingOutlined"
import PlusOutlined from "@ant-design/icons/lib/icons/PlusOutlined"
import getBase64 from "../image_ase64"
import PropTypes from 'prop-types'
import UploadOutlined from "@ant-design/icons/es/icons/UploadOutlined"
import "./index.less"

//TODO:优化,如果更新文件,则删除旧文件
const videoUrl = (serverFile, value, valueToUrl) => {
  if (!valueToUrl) return undefined;
  if (serverFile && serverFile.id) {
    return valueToUrl(serverFile.id)
  }
  if (value) {
    return valueToUrl(value)
  }
  return undefined
}

const SingleVideoUploader = (props) => {
  const [serverFile, $serverFile] = useState({})
  const [loading, $loading] = useState(false)
  const [fileName, $fileName] = useState()
  const [percent, $percent] = useState(0)

  const {onChange, value, valueToUrl, ...inherit} = props
  const onFileChange = ({file, event}) => {
    $loading(file.status === 'uploading')
    $percent(event ? parseInt(event.percent) : 0)
    $fileName(file.name)
    if (file.status === 'done') {
      const serverFileRecord = read(file, 'response.data')
      $loading(false)
      $serverFile(serverFileRecord)
      onChange(serverFileRecord)
    }
  }
  const url = videoUrl(serverFile, value, valueToUrl)
  return (
    <div className={'video-uploader'}>
      {
        !url
          ? undefined
          :
          <div>
            <video controls="controls"
                   src={url}
                   autoPlay={false}/>
          </div>
      }
      <Upload {...inherit}
              accept={'video/*'}
              showUploadList={false}
              multiple={false}
              onChange={onFileChange}
              withCredentials={true}>
        <div className={'video-uploader-progress'}>
          {percent ? <Progress percent={percent} size={'small'} steps={100} strokeColor="#1890ff"/> : undefined}
        </div>
        <Button type={'primary'}>
          {loading ? <LoadingOutlined/> : <UploadOutlined/>} 上传视频文件
        </Button>
        <span className={'video-uploader-file-name'}>{fileName}</span>
      </Upload>
    </div>
  )
}

SingleVideoUploader.propTypes = {
  /**上传服务器地址*/
  action: PropTypes.string.isRequired,
  /**设置值,一般为已有图片id*/
  value: PropTypes.string,
  /**通过值铆取一个已有图片地址函数*/
  valueToUrl: PropTypes.func,
  /**按钮显示文字*/
  label: PropTypes.string
}

//单张图片上传
export default SingleVideoUploader